<template>
	<div class="singer" ref="singer">
		<list-view @select="selectSinger" :data="singers" ref="list"></list-view>
		<router-view></router-view>
	</div>
</template>

<script>
	import { getSingerList } from '@/api/singer'
	import { ERR_OK } from '@/api/config'
	import  Singer from '@/common/js/singer'
	import ListView from '@/base/listview/listview'
	// vuex 提供的语法糖
	import { mapMutations } from 'vuex' 
	import { playlistMixin } from '@/common/js/mixin'


	const HOT_NAME = '热门' //热门数据
	const HOT_SINGER_LEN = 10 
	export default {
		mixins: [playlistMixin],
		// 获取数据的逻辑
		data() {
			return {
				singers: []
			}
		},
		created() {
			this._getSingerList()
		},
		methods: {
			handlePlaylist (playlist) {
				const bottom = playlist.length > 0 ? '60px' : ''
				this.$refs.singer.style.bottom = bottom
				this.$refs.list.refresh()
			},
			selectSinger(singer) {
				this.$router.push({
					path: `/singer/${singer.id}`
				})
				// 通过调用 this.setSinger(singer) 数据传进来
				this.setSinger(singer)
			},
			_getSingerList() {
				getSingerList().then((res) => {
					if (res.code === ERR_OK) {
						this.singers = this._normalizeSinger(res.data.list)
					}
				})
			},
			// 把其变为可用数据
			_normalizeSinger(list) {
				// 遍历数据
				let map = {
					hot: {
						title: HOT_NAME,
						items: []
					}
				}
				list.forEach((item, index) => {
					if (index < HOT_SINGER_LEN) {
						// 向items添加数据
						map.hot.items.push(new Singer({
							id: item.Fsinger_mid,
							name: item.Fsinger_name
						}))
					}
					const key = item.Findex
					if (!map[key]) {
						map[key] = {
							title: key,
							items: []
						}
					}
					map[key].items.push(new Singer({
							id: item.Fsinger_mid,
							name: item.Fsinger_name
					}))
				})
				// 为了得到有序列表我们需要处理 map
				let hot = []
				let ret = []
				for (let key in map) {
					let val = map[key]
					// 判断title是不是a-z A-Z
					if ( val.title.match(/[a-zA-Z]/)) {
						ret.push(val)
					} else if (val.title === HOT_NAME) {
						hot.push(val)
					}
				}
				// 排序 a-z
				ret.sort((a, b) => {
					return a.title.charCodeAt(0) - b.title.charCodeAt(0)
				})
				return hot.concat(ret)
			},
			// 在 methods 里面做对象的映射
			// 把mutations的修改映射成一个方法名
			...mapMutations({
				setSinger: 'SET_SINGER'
			})
		},
		components: {
			ListView
		}
	}
</script>

<style lang="stylus" scoped>
	.singer
		position: fixed
		top: 88px
		bottom: 0
		width: 100%		
</style>